package com.szh.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.szh.wechat.mapper.MessageMapper;
import com.szh.wechat.mapper.UserMapper;
import com.szh.wechat.model.Message;
import com.szh.wechat.model.User;
import com.szh.wechat.netty.NettyConfig;
import com.szh.wechat.service.MessageService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 罗兴发
 * @data 2025/2/17 10:58
 * @description：
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Resource
    MessageMapper messageMapper;
    @Resource
    UserMapper userMapper;
    @Override
    public void addMessage(String messageBody) {
        log.info("已进入存储消息业务实现层");
        //时间规格化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());
        //String转为Json格式
        JSONObject data = JSON.parseObject(messageBody);
        log.info("消息体：{}",data);
        //发送者用户ID
        String fromId = data.getString("fromId");
        String toId = data.getString("toId");
        String message = data.getString("message");
        //存入数据库
        Message m = new Message();
        m.setFUserId(Integer.valueOf(fromId));
        m.setUserId(Integer.valueOf(toId));
        m.setMessage(message);
        m.setAddTime(addTime);
        //list封装
        List<Message> list = new ArrayList<>();
        list.add(m);
        //持久层添加
        int k = messageMapper.addMessage(list);
        if (k<0)log.info("历史消息存储失败");
        else log.info("历史消息存储成功");
    }

    @Override
    public String pushMsgToUser(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        String userId = json.getString("user_id");
        String msg = json.getString("msg");
        Channel channel = NettyConfig.getChannel(userId);
        if (Objects.isNull(channel)) {

            js.put("code",500);
            js.put("msg","未连接socket服务器");

            //抛出异常
            throw new RuntimeException("未连接socket服务器");
        }else {
            //查询用户信息
            User user = userMapper.selectByUserId(userId);
            //发送消息
            channel.writeAndFlush(new TextWebSocketFrame(msg));

            js.put("code",200);
            js.put("msg","给【用户:"+user.getUsername()+"】发送消息成功，发送消息内容为：【"+msg+"】");
            getIpAddressOne(request);
        }

        return JSON.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String pushToAll(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        String msg = json.getString("msg");
        //发送消息
        NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));

        js.put("code",200);
        js.put("msg","消息群发成功");
        return JSON.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }

    /**
     * 小程序获取用户IP地址
     * @return
     */
    public String getIpAddressOne(HttpServletRequest req){
        //请求地址
        String infoUrl = "http://ip-api.com/json"; // lang参数是返回国家地区语言版本，zh_CN是中文简体
        log.info("地址为："+infoUrl);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //请求
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<String> responseString = restTemplate.postForEntity(infoUrl, request, String.class);
        String s = responseString.toString();
        log.info("用户访问网站获取到的IP信息为："+s);
        int i1 = s.indexOf("{");
        int i2 = s.indexOf("}");
        String sub = s.substring(i1, i2+1);
        log.info("截取的数据信息为："+sub);
        JSONObject json = JSON.parseObject(sub);
        String ip = json.getString("query");
        log.info("用户访问网站拿到的IP为："+ip);
        return ip;
    }
}
